const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");
const image = new Image();

const RADIUS = 100;
let imageData = null;
let magnifyingGlassX, magnifyingGlassY;
let magnifyRectangle = {};
let magnificationScale = 2;

function windowToCanvas(x, y) {
    const bbox = canvas.getBoundingClientRect();
    return {
        x: x - bbox.left * (bbox.width / canvas.width),
        y: y - bbox.top * (bbox.height / canvas.height)
    };
}

function drawImageBackground() {
    image.src = "./pic.png";
    image.onload = () => {
        context.drawImage(image, 0, 0);
    };
}

function drawMagnifyingGlass({ x, y }) {
    let scaledMagnifyRectangle;

    magnifyingGlassX = x;
    magnifyingGlassY = y;

    magnifyRectangle.x = x - RADIUS;
    magnifyRectangle.y = y - RADIUS;
    magnifyRectangle.width = RADIUS * 2 + 2 * context.lineWidth;
    magnifyRectangle.height = RADIUS * 2 + 2 * context.lineWidth;

    imageData = context.getImageData(
        magnifyRectangle.x,
        magnifyRectangle.y,
        magnifyRectangle.width,
        magnifyRectangle.height
    );

    context.save();
    scaledMagnifyRectangle = {
        width: magnifyRectangle.width * magnificationScale,
        height: magnifyRectangle.height * magnificationScale
    };
    context.beginPath();
    context.arc(
        magnifyingGlassX,
        magnifyingGlassY,
        RADIUS,
        0,
        Math.PI * 2,
        false
    );
    context.clip();
    context.drawImage(
        canvas,
        magnifyRectangle.x,
        magnifyRectangle.y,
        magnifyRectangle.width,
        magnifyRectangle.height,
        magnifyRectangle.x +
            magnifyRectangle.width / 2 -
            scaledMagnifyRectangle.width / 2,
        magnifyRectangle.y +
            magnifyRectangle.height / 2 -
            scaledMagnifyRectangle.height / 2,
        scaledMagnifyRectangle.width,
        scaledMagnifyRectangle.height
    );
    context.restore();
}

function eraserMagnifyingGlass() {
    if (imageData) {
        context.putImageData(imageData, magnifyRectangle.x, magnifyRectangle.y);
    }
}

drawImageBackground();

canvas.addEventListener("mousemove", e => {
    eraserMagnifyingGlass();
    drawMagnifyingGlass(windowToCanvas(e.clientX, e.clientY));
});
